package com.pack.shiro;

import com.pack.ToolEntity.BpmUtils;
import com.pack.bean.User;
import com.pack.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShiroManager extends AuthorizingRealm {

    //依赖注入
    @Autowired
    private UserService userService ;

    //权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("jinru");
     String username = principalCollection.getPrimaryPrincipal().toString();
     SimpleAuthorizationInfo info  = new SimpleAuthorizationInfo();

        System.out.println(username+"===============");

        //获取权限信息
        List<User> users = userService.findPermissionList(new User(username));
        if(BpmUtils.listIsNull(users)){
            for (User user : users) {
                info.addStringPermission(user.getPermissionName());
                System.out.println(user.getPermissionName()+"------------------");
            }
        }

        //获取角色信息
        List<User> userList = userService.findRoleList(new User(username));
        if(BpmUtils.listIsNull(userList)){
            for (User user : userList) {
                info.addRole(user.getRoleName());
                System.out.println(user.getRoleName()+"------------------");
            }
        }
        return info;
    }

    //登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("首先进入");
        String username = authenticationToken.getPrincipal().toString();
        String password = new String((char[])authenticationToken.getCredentials());
        System.out.println(username+"----------"+password);
        User user  = new User();
        user.setName(username);
        user.setPassword(password);
        List<User> us = userService.findList(user);
        if(us!=null){
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getName(),user.getPassword(),
                    "a") ;
            return authenticationInfo ;
        }else{
            return null;
        }
   }



}